<template>
  <a-modal
    title="编辑账单"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <h3>租客未能按時交租,重新約定收租日期</h3>
        <a-form-item v-show="false"><a-input v-decorator="['id']" /></a-form-item>
        <a-form-item
          label="新收租日"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
          <a-date-picker style="width: 100%" placeholder="請選擇新收租日" v-decorator="['rentedDay', { rules: [{ required: true, message: '請選擇新收租日！' }]}]" @change="onChangerentedDay"/>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import moment from 'moment'
  import { houseBillTuoQianEdit } from '@/api/modular/main/housebill/houseBillManage'
  export default {
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        rentedDayDateString: '',
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this)
      }
    },
    methods: {
      moment,
      // 初始化方法
      edit (record) {
        this.visible = true
        setTimeout(() => {
          this.form.setFieldsValue(
            {
              id: record.id
            }
          )
        }, 100)
        // 时间单独处理
        if (record.rentedDay != null) {
            this.form.getFieldDecorator('rentedDay', { initialValue: moment(record.rentedDay, 'YYYY-MM-DD') })
        }
        this.rentedDayDateString = moment(record.rentedDay).format('YYYY-MM-DD')
      },
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            for (const key in values) {
              if (typeof (values[key]) === 'object') {
                values[key] = JSON.stringify(values[key])
              }
            }
            values.editType = 'tq'
            values.rentedDay = this.rentedDayDateString
            houseBillTuoQianEdit(values).then((res) => {
              if (res.code === 200) {
                this.$message.success('修改成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error(res.msg)//  + res.message
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      onChangerentedDay(date, dateString) {
        this.rentedDayDateString = dateString
      },
      handleCancel () {
        this.form.resetFields()
        this.visible = false
      }
    }
  }
</script>
